package com.sgb.kjwl.view.widget;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.PopwindowCarTypeAndLenBinding;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.utils.DefaultUtil;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.PopViewHolder;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

/**
 * 车辆车长与车型选择弹窗
 */
public class CarTypeAndLenPopWindow extends BasePopWindow<Object> implements View.OnClickListener {
    private PopwindowCarTypeAndLenBinding mBinding;
    //车型/车长列表
    private List<GoodsInfoTypeEntity3> mCarTypeList;
    private CarTypeAdapter mCarTypeAdapter;
    private List<GoodsInfoTypeEntity3> mCarLenList;
    private CarLenAdapter mCarLenAdapter;
    //回调接口
    private Callback mCallback;

    public interface Callback {
        void result(List<GoodsInfoTypeEntity3> carTypeList, List<GoodsInfoTypeEntity3> carLenList);
    }

    public void addCallback(Callback mCallback) {
        this.mCallback = mCallback;
    }

    public CarTypeAndLenPopWindow(Context context) {
        super(context, DIR_DOWN_UP);
    }

    @Override
    protected int popLayout() {
        return R.layout.popwindow_car_type_and_len;
    }

    @Override
    protected void initView(PopViewHolder holder) {
        mBinding = (PopwindowCarTypeAndLenBinding) holder.getmBinding();
        initRecycler();
        initEvent();
    }

    private void initRecycler() {
        //车型列表
        mCarTypeList = new ArrayList<>();
        mCarTypeAdapter = new CarTypeAdapter(mCarTypeList);
        mBinding.rvCarType.setNestedScrollingEnabled(false);
        mBinding.rvCarType.setLayoutManager(new GridLayoutManager(mContext, 4));
        DividerDecoration.builder(mContext)
                .color(Color.TRANSPARENT)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.rvCarType);
        mCarTypeAdapter.bindToRecyclerView(mBinding.rvCarType);
        //车长列表
        mCarLenList = new ArrayList<>();
        mCarLenAdapter = new CarLenAdapter(mCarLenList);
        mBinding.rvCarLen.setNestedScrollingEnabled(false);
        mBinding.rvCarLen.setLayoutManager(new GridLayoutManager(mContext, 4));
        DividerDecoration.builder(mContext)
                .color(Color.TRANSPARENT)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.rvCarLen);
        mCarLenAdapter.bindToRecyclerView(mBinding.rvCarLen);
    }

    private void initEvent() {
        mBinding.setOnClick(this);
        mCarTypeAdapter.setOnItemClickListener((adapter, view, position) -> {
            GoodsInfoTypeEntity3 entity = mCarTypeList.get(position);
            if (mCarTypeAdapter.haveCache(entity)) {
                mCarTypeAdapter.removeCache(entity);
            } else {
                mCarTypeAdapter.putCache(entity);
            }
            //刷新车型列表
            mCarTypeAdapter.notifyDataSetChanged();
            //同步车长数据
            syncCarLenData();
        });
        mCarLenAdapter.setOnItemClickListener((adapter, view, position) -> {
            GoodsInfoTypeEntity3 entity = mCarLenList.get(position);
            if (mCarLenAdapter.haveCache(entity)) {
                mCarLenAdapter.removeCache(entity);
            } else {
                mCarLenAdapter.putCache(entity);
            }
            mCarLenAdapter.notifyDataSetChanged();
        });
    }

    /**
     * 同步车长数据
     */
    private void syncCarLenData() {
        //获取车型对应的车长数据
        List<GoodsInfoTypeEntity3> lenList = new ArrayList<>();
        HashMap<String, GoodsInfoTypeEntity3> cache = mCarTypeAdapter.getCache();
        for (GoodsInfoTypeEntity3 type : cache.values()) {
            if (type.getCarLenList() != null && type.getCarLenList().size() > 0) {
                lenList.addAll(type.getCarLenList());
            }
        }
        //刷新车长数据
        mCarLenAdapter.refreshCurrentLenData(lenList);
    }

    /**
     * 设置车型数据
     */
    public void setCarTypeData(List<GoodsInfoTypeEntity3> list) {
        //初始化数据
        if (list == null) return;
        mCarTypeList.clear();
        //添加车型数据
        mCarTypeList.addAll(list);
        mCarTypeAdapter.notifyDataSetChanged();
    }

    /**
     * 设置车长数据
     */
    public void setCarLenData(List<GoodsInfoTypeEntity3> list) {
        //初始化数据
        if (list == null) return;
        mCarLenList.clear();
        //添加车型数据
        mCarLenList.addAll(list);
        mCarLenAdapter.notifyDataSetChanged();
    }

    /**
     * 设置选中的车型
     */
    public void setSelectedCarType(List<GoodsInfoTypeEntity3> list) {
        if (mCarTypeList.isEmpty()) return;
        for (GoodsInfoTypeEntity3 entity : list) {
            //从数据列表中筛选出选中车型，附带车长数据
            for (GoodsInfoTypeEntity3 type : mCarTypeList) {
                if (!TextUtils.isEmpty(type.getNo()) && type.getNo().equals(entity.getNo())) {
                    mCarTypeAdapter.putCache(type);
                    break;
                }
            }
        }
        mCarTypeAdapter.notifyDataSetChanged();
        //同步车长数据
        syncCarLenData();
    }

    /**
     * 设置选中的车长
     */
    public void setSelectedCarLen(List<GoodsInfoTypeEntity3> list) {
        for (GoodsInfoTypeEntity3 entity : list) {
            mCarLenAdapter.putCache(entity);
        }
        mCarLenAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        if (v == mBinding.tvCancel) {
            dismiss();
        } else if (v == mBinding.tvSubmit) {
            confirm();
        }
    }

    /**
     * 确认选择数据
     */
    private void confirm() {
        //检查组装数据
        if (mCarTypeAdapter.getCache().isEmpty()) {
            MToast.showToast(mContext, "请选择车型");
            return;
        }
        if (mCarLenAdapter.getCache().isEmpty()) {
            MToast.showToast(mContext, "请选择车长");
            return;
        }
        //获取选中缓存数据
        HashMap<String, GoodsInfoTypeEntity3> carTypeCache = mCarTypeAdapter.getCache();
        HashMap<String, GoodsInfoTypeEntity3> carLenCache = mCarLenAdapter.getCache();
        //初始化返回数据
        List<GoodsInfoTypeEntity3> carTypeList = new ArrayList<>(carTypeCache.values());
        List<GoodsInfoTypeEntity3> carLenList = new ArrayList<>();
        //车长no缓存，筛除重复数据
        HashSet<String> noSet = new HashSet<>();
        //检查添加车长
        for (GoodsInfoTypeEntity3 carType : carTypeList) {
            Log.d("typeAndLen", String.format("carType&no=%s&%s", carType.getName(), carType.getNo()));
            if (carType.getCarLenList() == null) continue;
            for (GoodsInfoTypeEntity3 carLen : carType.getCarLenList()) {
                //检查当前选中车型包含的车长列表，如果包含当前车长且没有重复则添加
                if (carLenCache.containsKey(carLen.getName()) && !noSet.contains(carLen.getNo())) {
                    Log.d("typeAndLen", String.format("carLen&no=%s&%s", carLen.getName(), carLen.getNo()));
                    carLenList.add(carLen);
                    //添加缓存,防重复
                    noSet.add(carLen.getNo());
                }
            }
        }
        //返回选中数据
        if (mCallback != null) {
            mCallback.result(carTypeList, carLenList);
        }
        dismiss();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        clearAlpha();
    }

    /**
     * 车型适配器
     */
    private static class CarTypeAdapter extends BaseQuickAdapter<GoodsInfoTypeEntity3, BaseViewHolder> {
        //车型使用no做唯一标识
        private final HashMap<String, GoodsInfoTypeEntity3> mSelect = new HashMap<>();

        public CarTypeAdapter(@Nullable List<GoodsInfoTypeEntity3> data) {
            super(R.layout.item_pop_car_type, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, GoodsInfoTypeEntity3 item) {
            helper.setText(R.id.tv_item_pop_car_type, DefaultUtil.getString(item.getName()))
                    .getView(R.id.tv_item_pop_car_type).setSelected(haveCache(item));
        }

        /**
         * 判断缓存是否包含当前项
         */
        public boolean haveCache(GoodsInfoTypeEntity3 entity) {
            return mSelect.containsKey(entity.getNo());
        }

        /**
         * 添加选中缓存
         */
        public void putCache(GoodsInfoTypeEntity3 entity) {
            if (entity == null || haveCache(entity)) return;
            if (mSelect.size() >= 3) {
                MToast.showToast(mContext, "最多选择三项");
                return;
            }
            mSelect.put(entity.getNo(), entity);
        }

        /**
         * 移除选中缓存
         */
        public void removeCache(GoodsInfoTypeEntity3 entity) {
            if (entity == null) return;
            mSelect.remove(entity.getNo());
        }

        /**
         * 获取缓存
         */
        public HashMap<String, GoodsInfoTypeEntity3> getCache() {
            return mSelect;
        }

        /**
         * 清空缓存
         */
        public void clearCache() {
            mSelect.clear();
        }
    }

    /**
     * 车长适配器
     */
    private static class CarLenAdapter extends BaseQuickAdapter<GoodsInfoTypeEntity3, BaseViewHolder> {
        //车长因为不同车型下车长no不同，所以使用name做唯一标识
        private final HashMap<String, GoodsInfoTypeEntity3> mSelect = new HashMap<>();
        //当前选中车型对应的车长数据
        private final HashMap<String, GoodsInfoTypeEntity3> mCurrentLen = new HashMap<>();

        public CarLenAdapter(@Nullable List<GoodsInfoTypeEntity3> data) {
            super(R.layout.item_pop_car_len, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, GoodsInfoTypeEntity3 item) {
            TextView len = helper.getView(R.id.tv_item_pop_car_len);
            len.setText(DefaultUtil.getString(item.getName()));
            //设置选中
            len.setSelected(haveCache(item));
            //设置当前车长是否可用
            if (mCurrentLen.containsKey(item.getName())) {
                len.setAlpha(1f);
                len.setEnabled(true);
            } else {
                len.setAlpha(0.5f);
                len.setEnabled(false);
            }
        }

        /**
         * 刷新当前可用车长数据
         */
        public void refreshCurrentLenData(List<GoodsInfoTypeEntity3> lenList) {
            mCurrentLen.clear();
            if (lenList != null && lenList.size() > 0) {
                for (GoodsInfoTypeEntity3 entity : lenList) {
                    mCurrentLen.put(entity.getName(), entity);
                }
            }
            //检查并删除不可选的车长数据
            Iterator<String> iterator = mSelect.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                //如果当前车长数据不包含已选中的车长则删除选中车长数据
                if (!mCurrentLen.containsKey(key)) {
                    iterator.remove();
                }
            }
            //刷新列表
            notifyDataSetChanged();
        }

        /**
         * 判断缓存是否包含当前项
         */
        public boolean haveCache(GoodsInfoTypeEntity3 entity) {
            return mSelect.containsKey(entity.getName());
        }

        /**
         * 添加选中缓存
         */
        public void putCache(GoodsInfoTypeEntity3 entity) {
            if (entity == null || haveCache(entity)) return;
            if (mSelect.size() >= 3) {
                MToast.showToast(mContext, "最多选择三项");
                return;
            }
            mSelect.put(entity.getName(), entity);
        }

        /**
         * 移除选中缓存
         */
        public void removeCache(GoodsInfoTypeEntity3 entity) {
            if (entity == null) return;
            mSelect.remove(entity.getName());
        }

        /**
         * 获取缓存
         */
        public HashMap<String, GoodsInfoTypeEntity3> getCache() {
            return mSelect;
        }

        /**
         * 清空缓存
         */
        public void clearCache() {
            mSelect.clear();
        }
    }
}
